package com.qingluan.pyi;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.data.Personal_Info_database;


import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.AutoCompleteTextView.OnDismissListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	private AutoCompleteTextView account;
	private EditText password;
	private Button login_user;
	//private Button create_user;
	private Animation anim_down_appearce;
	private Animation anim_up_gone;
	private int STATUE = R.string.InitState;
	private int LOGIN_STATE ;
	private int Times = 3;
	
	//finger arguments area 
	private int login_state_pre = 0;
	private int login_state_input = 1;
	private float startX ;
	private  boolean IS_RECOREDED = false;
	private final int IS_SEND_INTENT = 1;
	private final int NO_SEND_INTENT =0;
	private int NOW_STATE ;
	//login url 
	private String URL_LOGIN = ARGUMENTS.URL_ROOT + "login";
	private boolean result;
	private boolean UNLOCK = false;
	
	//intent area
	private Intent intent_to_sign;
	private Context context_this_activity ;
	private ArrayList<String> accounts_content ;
    @SuppressLint("NewApi") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context_this_activity = getApplicationContext();
		accounts_content  = InitAutoCompleteTextData();
		
		
        account = (AutoCompleteTextView)findViewById(R.id.Account);
		password = (EditText)findViewById(R.id.textPassword);
		
		
		/*
		 * set adapter for auto-complete-text
		 */
		ArrayAdapter<String> itemNameAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line,accounts_content);
		account.setAdapter(itemNameAdapter);
		
		account.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				TextView content = (TextView) arg0.findViewById(android.R.id.text1);
				String account  = content.getText().toString();
				Personal_Info_database DB=  new Personal_Info_database(context_this_activity);
				String user = DB.getUserByEmail(account);
				String pass = DB.searchPassword(user);
				String name = DB.searchName(user);
				/*
				new AlertDialog.Builder(LoginActivity.this)
				.setTitle("info")
				.setMessage("account : "+account +"pass is :"+ pass+"/"+name+"/"+user)
				.show();
				*/
				if (pass != null){
					password.setText(pass);
				}
				//Toast.makeText(context_this_activity
					//	, account+"/"+user+"/"+pass
						//, Toast.LENGTH_SHORT)
						//.show();
				
				
			}
			
		});
		
		
		login_user = (Button)findViewById(R.id.login);
		anim_down_appearce = AnimationUtils.loadAnimation(getApplicationContext()
				, R.anim.search_anim);
		
		anim_up_gone = AnimationUtils.loadAnimation(getApplicationContext()
				, R.anim.search_anim_2);
		
		anim_down_appearce.setFillAfter(true);
		anim_up_gone.setFillAfter(true);
		account.setAlpha(0);
		password.setAlpha(0);
		
		// state set initialization
		LOGIN_STATE = login_state_pre;
		NOW_STATE = NO_SEND_INTENT;
    }

	@SuppressLint("NewApi")
	public void login_user(View view) throws JSONException{
		if (LOGIN_STATE == login_state_pre){
			Log.d("I_GET","editable");
			account.startAnimation(anim_down_appearce);
			password.startAnimation(anim_down_appearce);
			account.setAlpha(200);
			password.setAlpha(200);
			account.setFocusable(true);
			
			//Database loading..
			accounts_content  = InitAutoCompleteTextData();
			

			account.setFocusableInTouchMode(true);
			password.setFocusable(true);
			password.setFocusableInTouchMode(true);
			
			LOGIN_STATE = login_state_input;
			STATUE = R.string.LoginState;

			Log.d("I_GET","login state :" +String.valueOf(LOGIN_STATE));
		}else if (LOGIN_STATE== login_state_input){
			String info = account.getText().toString();
			String pass = password.getText().toString();
			Log.d("I_GET","uneditable");
			account.startAnimation(anim_up_gone);
			password.startAnimation(anim_up_gone);
			
			account.setFocusable(false);
			password.setFocusable(false);

			account.setFocusableInTouchMode(false);
			password.setFocusableInTouchMode(false);
			LOGIN_STATE = login_state_pre;
			STATUE = R.string.InitState;
			Log.d("I_GET","login state :" +String.valueOf(LOGIN_STATE));
			Judege(info,pass);

		}
	}

    
    
    private boolean Judege(final String phone_or_email, String pass) throws JSONException {
		// TODO Auto-generated method stub
    	final String Tag_email_or_phone = email_or_phone(phone_or_email);
    	final Personal_Info_database db = new Personal_Info_database(context_this_activity);
    	
    	JSONObject login_json = new JSONObject();
    	
    	
		login_json.put("info", phone_or_email);
		login_json.put("password", pass);
    	
    	
    	final Intent intent = new Intent(LoginActivity.this,MainActivity.class);
    	AsyncHttpClient  client = new AsyncHttpClient();
    	client.setTimeout(10000);
    	RequestParams params = new RequestParams();
    	params.put(ARGUMENTS.JSON_LOGIN_POST, login_json.toString());
    	client.post(this.URL_LOGIN, params,new AsyncHttpResponseHandler(){
    		@Override
    		public void onSuccess(String object){
    			try {
					JSONObject json_response = new JSONObject(object);
					
					// get right response
					if (json_response.get("response").equals("ok")){
						result = true;
						String uid = null;
						if (Tag_email_or_phone.equals("email")){
							String user = db.getUserByEmail(phone_or_email);
							uid = db.searchPhone(user);
							db.cloase();
						}else {
							uid = phone_or_email;
						}
						//record account 
						String user_phone = json_response.getString("phone");
						String user_email = json_response.getString("email");
						String user_name = json_response.getString("name");
						Personal_Info_database DB = new Personal_Info_database(context_this_activity);
						ContentValues people_values = new ContentValues();
						people_values.put("uid", user_phone);
						people_values.put("name", user_name);
						people_values.put("email", user_email);
						
						String ifNull = DB.searchEmail(user_phone) ;
						if (ifNull == null){
							
							DB.insertMyTag(people_values);
							DB.cloase();
						}
						
						
				    	intent.putExtra("uid", uid);
						Toast.makeText(context_this_activity, "T T"+result+ifNull, Toast.LENGTH_SHORT).show();
						LoginActivity.this.startActivity(intent);
					}else {
						Toast.makeText(context_this_activity
								, json_response.get("response").toString()
								, Toast.LENGTH_SHORT)
								.show();
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    		@Override
    		public void onFailure(Throwable error,String message){
    			Toast.makeText(getApplicationContext(), "Error : "+message,Toast.LENGTH_SHORT).show();
    		}
    	});
    	Log.d("I_GET","now : "+result);
    	
    	/*
    	 * 
    	 * 测试用 用完后一定要删除
    	 */
//    	
//    	String uid = null;
//    	
//    	if (Tag_email_or_phone.equals("email")){
//			String user = db.getUserByEmail(phone_or_email);
//			uid = db.searchPhone(user);
//		}else {
//			uid = phone_or_email;
//		}
//    	
//    	Log.d("I_GET","tag :"+Tag_email_or_phone +" uid : "+uid);
//    	intent.putExtra("uid", uid);
//    	LoginActivity.this.startActivity(intent);
//		
		return false;
	}
    
    
    
    public boolean onKeyDown(int keycode,KeyEvent event){
    	if (keycode == KeyEvent.KEYCODE_BACK){
    		if (STATUE == R.string.LoginState){
    			account.startAnimation(anim_up_gone);
    			password.startAnimation(anim_up_gone);
    			account.setFocusable(false);
				account.setFocusableInTouchMode(false);
				password.setFocusable(false);
				password.setFocusableInTouchMode(false);
				
				LOGIN_STATE = login_state_pre;
				Log.d("I_GET","login state :" +String.valueOf(LOGIN_STATE));
				STATUE = R.string.InitState;
    		}else if (STATUE == R.string.InitState){
    			Log.d("I_GET","this is ....TAG");
    			 //exit this application
    			android.os.Process.killProcess(android.os.Process.myPid());
    			
    		}
    	}
    	return false;
    }
    
	
	
	@Override
	public boolean onTouchEvent(MotionEvent ev){
		if(UNLOCK ==false){
			float tempX = ev.getX();
			switch (ev.getAction()){
				case MotionEvent.ACTION_DOWN:
					startX = ev.getX();
					IS_RECOREDED = true;
					break;
				case MotionEvent.ACTION_MOVE:
					//Log.d("I_GET","坐标 startX"+ String.valueOf(startX) + "tempX : "+String.valueOf(tempX) + "状态: "+this.IS_RECOREDED);
					if (startX - tempX > 200){
						Log.d("I_GET","test time");
						UNLOCK = true;
						NOW_STATE = IS_SEND_INTENT;
						DoByState();
					}else{
						NOW_STATE = NO_SEND_INTENT;
					}
					break;
				case MotionEvent.ACTION_UP:
					
					break;
				default:
					break;
			}
			Log.d("I_GET","s"+String.valueOf(startX)+"now :"+String.valueOf(tempX));
		}
		//this.IS_RECOREDED = false;
		return false;
	}
	 
	public void DoByState(){
		switch (NOW_STATE){
		case IS_SEND_INTENT:
			//intent_to_sign = new Intent(LoginActivity.this,MapMainActivity.class);
			intent_to_sign = new Intent(LoginActivity.this,SignUpActivity.class);
			LoginActivity.this.startActivity(intent_to_sign);
			break;
		case NO_SEND_INTENT:
			
			break;
		default:
			break;
		}
		
	}
	
	public String email_or_phone (String info){
		byte[] temp_chars = info.getBytes();
		byte email = "@".getBytes()[0];
		String tag = "phone";
		for (byte i : temp_chars){
			if (String.valueOf(i).equals(String.valueOf(email))){
				Log.d("I_GET","i matched @");
				tag = "email";
			}
			Log.d("I_GET","i :" + String.valueOf(i));
		}
		return tag;
	}
	
	/*
	 * search all accounts info in DB.
	 */
	private ArrayList<String> InitAutoCompleteTextData(){
		
		Personal_Info_database DB = new Personal_Info_database(context_this_activity);
		ArrayList<String> accounts = new ArrayList<String>();
		Cursor c = DB.query(Personal_Info_database.TBL_NAME_MISSION);
		if(c.isLast()){
			c.close();
			DB.close();
		}
		
		if(c.moveToFirst()){
			String first_account_email = c.getString(c.getColumnIndex("email"));
			accounts.add(first_account_email);
			Log.d("I_GET","Account : "+first_account_email);
		}
		Log.d("I_GET","getting account..... ");
		while (c.moveToNext()){
			String account_email = c.getString(c.getColumnIndex("email"));
			Log.d("I_GET","Account : "+account_email);
			//Toast.makeText(context_this_activity, account_email, Toast.LENGTH_SHORT).show();
			accounts.add(account_email);
		}
		if (c.moveToLast()){
			Log.d("I_GET","found no account ...");
			c.close();
		}
		DB.close();
		
		return  accounts;
	}
	
	
	/*
	 * listen auto-complete-text-view that if changed .then get password
	 * which will pass to EditText (password)
 	 */

    
}
